package com.lineage.server.datatables;

import com.lineage.DatabaseFactory;
import com.lineage.server.datatables.lock.AccountReading;
import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.templates.L1Account;
import com.lineage.server.utils.PerformanceTimer;
import com.lineage.server.utils.SQLUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ItemRestrictionsTable {
  public static final ArrayList<Integer> RESTRICTIONS;
  
  private static final Log _log = LogFactory.getLog(ItemRestrictionsTable.class);
  
  private static ItemRestrictionsTable _instance;
  
  static {
    RESTRICTIONS = new ArrayList<>();
  }
  
  public static ItemRestrictionsTable get() {
    if (_instance == null)
      _instance = new ItemRestrictionsTable(); 
    return _instance;
  }
  
  private static void updata_name(int itemid) {
    Connection cn = null;
    PreparedStatement ps = null;
    String itemname = ItemTable.get().getTemplate(itemid).getName();
    try {
      cn = DatabaseFactory.get().getConnection();
      ps = cn.prepareStatement("UPDATE `server_item_restrictions` SET `名称`=? WHERE `itemid`=?");
      int i = 0;
      ps.setString(++i, "限制交易->" + itemname);
      ps.setInt(++i, itemid);
      ps.execute();
    } catch (SQLException e) {
      _log.error(e.getLocalizedMessage(), e);
    } finally {
      SQLUtil.close(ps);
      SQLUtil.close(cn);
    } 
  }
  
  public void load() {
    PerformanceTimer timer = new PerformanceTimer();
    Connection con = null;
    PreparedStatement pstm = null;
    ResultSet rs = null;
    try {
      con = DatabaseFactory.get().getConnection();
      pstm = con.prepareStatement("SELECT * FROM `server_item_restrictions`");
      rs = pstm.executeQuery();
      while (rs.next()) {
        int itemid = rs.getInt("itemid");
        String note = rs.getString("名称");
        if (!note.contains("=>"))
          updata_name(itemid); 
        RESTRICTIONS.add(Integer.valueOf(itemid));
      } 
    } catch (SQLException e) {
      _log.error(e.getLocalizedMessage(), e);
    } finally {
      SQLUtil.close(rs);
      SQLUtil.close(pstm);
      SQLUtil.close(con);
    } 
    _log
      .info("载入交易限制道具: " + RESTRICTIONS.size() + "(" + timer.get() + "ms)");
  }
  
  public boolean checkItemRestrictions(int itemId, L1PcInstance pc) {
    L1Account act = AccountReading.get().getAccount(pc.getAccountName());
    if (RESTRICTIONS.contains(Integer.valueOf(itemId)) || (act.get_friend() > 0 && ServerFriendItemShopTable.get().getMaxCount(itemId) < 0))
      return true; 
    return false;
  }
}
